# import path
import os
import sys

workdir = os.path.dirname(os.path.realpath(__file__))
libpath = os.path.join(workdir,'..','lib')
print libpath
sys.path.append(libpath)

import sqlpool
from mylib import log

class ftpCoord():
	def __init__(self,dbhash,type):
		self.con = sqlpool.SqlPool(
		    db     = dbhash['database'],
		    host   = dbhash['host'],
		    user   = dbhash['user'],
		    passwd = dbhash['password'],
		    #port   = dbhash['port']
		)
		self.table = dbhash['table']
		self.type = type
		self.addlock = False
		
	def __del__(self):
		if self.addlock:
			self.unlock()

	def setname(self,remote,local):
		self.remote = remote
		self.local = local
		
	def detectRunning(self):
		detectRunningSQL = "select count(1) from %s where status = 0" % (self.table)
		getData = self.con.query(detectRunningSQL)
		return getData[0][0]

	def detectrecord(self,filename):
		detectSQL = "select 1 from %s where `remote_file` = '%s'" % (self.table,filename)
		getData = self.con.query(detectSQL)
		if getData:
			return True
		else:
			return False

	def lock(self):
		lockSQL = "insert into %s (`type`,`remote_file`,`local_file`,`status`) VALUES ('%s','%s','%s','%d')" % (self.table,self.type,self.remote,self.local,0)
		if self.con.execute(lockSQL) < 0:
			log("Unable to lock this ftp job,maybe it was already started somewhere:\n\tyou can use defination cleanlocks() to get rid of the lock of this job,or delete the record in table `trs_record` manually.")
			return False
		else:
			self.addlock = True
			return True

	def cleanlocks(self):
		cleanlocksSQL = "delete from %s where `type`='%s' and `remote_file`='%s'" % (self.table,self.type,self.remote)
		affectRow = self.con.execute(cleanlocksSQL)
		if affectRow == 0:
			#log("lock not exists:table-%s type-%s remote_file-%s status-%s" % (self.table,self.type,self.remote,0))
			return True
		elif affectRow > 0 :
			log("clear the lock:table-%s type-%s remote_file-%s status-%s" % (self.table,self.type,self.remote,0))
			return True
		else:
			return False

	def unlock(self):
		unlockSQL = "delete from %s where `type`='%s' and `remote_file`='%s' and status='%d'" % (self.table,self.type,self.remote,0)
		if self.con.execute(unlockSQL) < 0:
			return False
		else:
			return True

	def badjob(self):
		badjobSQL = "update %s set status = %d where `type`='%s' and `remote_file`='%s'" % (self.table,-1,self.type,self.remote)
		if self.con.execute(badjobSQL) < 0:
			return False
		else:
			return True


	def goodjob(self):
		goodjobSQL = "update %s set status = %d where `type`='%s' and `remote_file`='%s'" % (self.table,1,self.type,self.remote)
		if self.con.execute(goodjobSQL) < 0:
			return False
		else:
			return True
		

